import socket


def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

    server_socket.bind(('',8080))

    server_socket.listen(128)

    while True:
        new_socket, new_address = server_socket.accept()
        print(f"{str(new_address)}已经上线")
        recv_data = new_socket.recv(4096)

        if not recv_data:
            print(f"{str(new_address)}下线了")
            new_socket.close()
            continue

        path_info = recv_data.decode().split(" ")[1]

        if path_info == "/":
            path_info = "/index.html"

        try:
            with open("static" + path_info, "rb") as file:
                file_data = file.read()
        except:
            with open("static/404.html", "rb") as file:
                file_data = file.read()
                http_data = 'HTTP/1.1 404 NOT Found\r\nServer: PWS\r\n\r\n'.encode() + file_data

        else:
            http_data = 'HTTP/1.1 200 OK\r\nServer: PWS\r\n\r\n'.encode() + file_data

        finally:

            new_socket.send(http_data)

            new_socket.close()


if __name__ == '__main__':
    main()